package com.clearliang.alarmnotice.view;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clearliang.alarmnotice.R;
import com.clearliang.alarmnotice.adapter.AlarmAdapter;
import com.clearliang.alarmnotice.bean.AlarmBean;
import com.clearliang.alarmnotice.service.CheckAlarmService;
import com.clearliang.alarmnotice.service.StartAlarmService;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import static com.clearliang.alarmnotice.view.GlobleConst.SP_ALARM;
import static com.clearliang.alarmnotice.view.GlobleConst.SP_ALARM_DETAILS;

public class MainActivity extends AppCompatActivity implements EditDialogFragment.OnResultListener {
    private RecyclerView recycler;
    private Button btnSetting;
    private Button btnStart;
    private Button btnCancel;
    private Button btnSave;
    private TextView tvTitle;
    private AlarmAdapter adapter;
    private List<AlarmBean> alarmList;
    private TextView tvTurn;
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    private boolean isCanSetting = true;   // 是否可以进行其他操作
    private boolean isSaveSetting = false; // 是否点击了保存

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initEvent();
        initRecycler();
    }

    private void initRecycler() {
        initData();
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(layoutManager);
        adapter = new AlarmAdapter(this, R.layout.item_alarm, alarmList);
        recycler.setAdapter(adapter);

        adapter.setOnSwClickListener(new AlarmAdapter.OnCardItemClickListener() {
            @Override
            public void clickSwitchListener(CompoundButton buttonView, AlarmBean item, int position, boolean isChecked) {
                if (isCanSetting) {
                    if (buttonView.isPressed()) {  // 这里需要加入是否点击的判断，否则会引起组件重置导致数据错乱
                        for (int i = 0; i < alarmList.size(); i++) {
                            if (alarmList.get(i).getId() == item.getId()) {
                                alarmList.get(i).setIsOpen(isChecked);
                                break;
                            }
                        }
                    }
                } else {
                    buttonView.setChecked(!isChecked);
                    ToastUtils.showShort("请先停止后再进行操作!");
                }
            }

            @Override
            public void clickLongListener(AlarmBean item, int position) {
                if (isCanSetting) {
                    showMessagePositiveDialog(position);
                } else {
                    ToastUtils.showShort("请先停止后再进行操作!");
                }
            }

            @Override
            public void clickListener(AlarmBean item, int position) {
                if (isCanSetting) {
                    EditDialogFragment editNameDialog = new EditDialogFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", JSON.toJSONString(item));
                    editNameDialog.setArguments(bundle);
                    editNameDialog.show(getSupportFragmentManager(), "EditDialog");
                } else {
                    ToastUtils.showShort("请先停止后再进行操作!");
                }
            }
        });
    }

    private void showMessagePositiveDialog(final int position) {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage("确定要删除吗？")
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        alarmList.remove(position);
                        ToastUtils.showShort("删除成功");
                        adapter.notifyDataSetChanged();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void initData() {
        alarmList = new ArrayList<>();
        String result = SPUtils.getInstance(SP_ALARM).getString(SP_ALARM_DETAILS, "");
        if (TextUtils.isEmpty(result)) {
            try {
                InputStreamReader isr = new InputStreamReader(getAssets().open(SP_ALARM), "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String line;
                StringBuilder builder = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    builder.append(line);
                }
                br.close();
                isr.close();

                JSONObject jsonObject = new JSONObject(builder.toString());
                JSONArray array = jsonObject.getJSONArray(SP_ALARM_DETAILS);
                String arr = array.toString();
                alarmList.addAll(JSON.parseArray(arr, AlarmBean.class));

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            alarmList.addAll(JSON.parseArray(result, AlarmBean.class));
        }
    }

    private void initEvent() {
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCanSetting) {
                    if (isSaveSetting) {
                        // 开启定时监听服务
                        isCanSetting = false;
                        Intent intent = new Intent(MainActivity.this, CheckAlarmService.class);
                        startService(intent);
                    } else {
                        ToastUtils.showShort("启动前请先点击保存!");
                    }
                } else {
                    ToastUtils.showShort("请先停止后再进行操作!");
                }

            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isCanSetting = true;
                isSaveSetting = false;

                Intent intentCheck = new Intent(MainActivity.this, CheckAlarmService.class);
                stopService(intentCheck);

                Intent intentStart = new Intent(MainActivity.this, StartAlarmService.class);
                stopService(intentStart);

                LogUtils.e("服务关闭");
                ToastUtils.showShort("服务关闭");
            }
        });
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCanSetting) {
                    isSaveSetting = true;
                    SPUtils.getInstance(SP_ALARM).put(SP_ALARM_DETAILS, JSON.toJSONString(alarmList));
                    final QMUITipDialog tipDialog = new QMUITipDialog.Builder(MainActivity.this)
                            .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                            .setTipWord("保存中")
                            .create();
                    tipDialog.show();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            tipDialog.dismiss();
                            ToastUtils.showShort("保存成功!");
                        }
                    }, 1500);
                } else {
                    ToastUtils.showShort("请先停止后再进行操作!");
                }

            }
        });
        btnSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCanSetting) {
                    showEditDialog();
                } else {
                    ToastUtils.showShort("请先停止后再进行操作!");
                }
            }
        });
        tvTurn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLongMessageDialog();
            }
        });
    }

    private void showLongMessageDialog() {
        new QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage(
                        getResources().getString(R.string.s_notice_1)
                )
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void initView() {
        recycler = (RecyclerView) findViewById(R.id.recycler);
        btnSetting = (Button) findViewById(R.id.btn_setting);
        btnSave = (Button) findViewById(R.id.btn_save);
        btnStart = (Button) findViewById(R.id.btn_start);
        btnCancel = (Button) findViewById(R.id.btn_cancel);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTurn = (TextView) findViewById(R.id.tv_turn);
    }

    public void showEditDialog() {
        EditDialogFragment editNameDialog = new EditDialogFragment();
        editNameDialog.show(getSupportFragmentManager(), "EditDialog");
    }

    @Override
    public void onTimeListener(String title, String content, String startTime, String endTime, List<String> weekday) {
        //LogUtils.e(title + "\n" + content + "\n" + startTime + ":00" + "-" + endTime + ":00" + "\n" + JSON.toJSONString(weekday));
        AlarmBean newAlarm = new AlarmBean();
        newAlarm.setId(alarmList.size() + 1);
        newAlarm.setName(title);
        newAlarm.setContent(content);
        newAlarm.setStartTime(startTime + ":00");
        newAlarm.setEndTime(endTime + ":00");
        newAlarm.setWeekday(weekday);
        newAlarm.setAudioUrl("www.baidu.com");
        newAlarm.setIsOpen(false);
        alarmList.add(0, newAlarm);
        adapter.notifyDataSetChanged();
        //LogUtils.e("添加后",JSON.toJSONString(alarmList));
    }

    @Override
    public void onTimeListener(AlarmBean alarmBean) {
        for (int i = 0; i < alarmList.size(); i++) {
            if (alarmList.get(i).getId() == alarmBean.getId()) {
                alarmList.get(i).setName(alarmBean.getName());
                alarmList.get(i).setContent(alarmBean.getContent());
                alarmList.get(i).setStartTime(alarmBean.getStartTime());
                alarmList.get(i).setEndTime(alarmBean.getEndTime());
                alarmList.get(i).setWeekday(alarmBean.getWeekday());
                alarmList.get(i).setIsOpen(alarmBean.isIsOpen());
                break;
            }
        }
        adapter.notifyDataSetChanged();
    }

    boolean mBound = false; //一开始，并没有和Service绑定.这个参数是用来显示绑定状态

    //匿名内部类：服务连接对象
    private ServiceConnection connection = new ServiceConnection() {

        //当服务异常终止时会调用。注意，解除绑定服务时不会调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false; //服务异常终止时，状态为未绑定
        }

        //和服务绑定成功后，服务会回调该方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            MyService.MyBinder myBinder = (MyService.MyBinder) service;
//            //在Activity中调用Service里面的方法
//            myBinder.startAlarm();
//            myBinder.stopAlarm();
//            mBound = true; //true说明是绑定状态
        }
    };

    private static long mPressedTime = 0;
    @Override
    public void onBackPressed() {
        long mNowTime = System.currentTimeMillis();//获取第一次按键时间
        if ((mNowTime - mPressedTime) > 2000) {//比较两次按键时间差
            ToastUtils.showShort("再按一次退出程序");
            mPressedTime = mNowTime;
        } else {//退出程序
            this.finish();
            System.exit(0);
        }
    }
}
